package com.qdxwx.manage.shiro;

import com.qdxwx.common.utils.BeanUtils;
import com.qdxwx.manage.shiro.realm.UserRealm;
import com.qdxwx.models.manager.Manager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * shiro 工具类
 * 
 * @author qdxwx
 */
public class ShiroUtils {

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        getSubject().logout();
    }

    public static Manager getManager() {
        Manager manager = null;
        Object obj = getSubject().getPrincipal();
        if ((null != obj)) {
            manager = new Manager();
            BeanUtils.copyBeanProp(manager, obj);
        }
        return manager;
    }

    public static void setManager(Manager manager) {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(manager, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static void clearCachedAuthorizationInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        UserRealm realm = (UserRealm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }

    public static Integer getManagerId() {
        Manager manager = getManager();
        if (null != manager) {
            return manager.getManagerId();
        }
        return 0;
    }

    public static String getLoginName() {
        Manager manager = getManager();
        if (null != manager) {
            return manager.getLoginName();
        }
        return "";
    }

    public static String getIp() {
        return getSubject().getSession().getHost();
    }

    public static String getSessionId() {
        return String.valueOf(getSubject().getSession().getId());
    }

    //获取机构ID
    public static Integer getCompanyId() {
        Manager manager = getManager();
        if (null != manager) {
            return manager.getCompanyId();
        }
        return 0;
    }

    //判断权限
    public static boolean isPermitted(String s) {
        return getSubject().isPermitted(s);
    }
}
